/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ntb.controllers;

import com.ntb.common.SecuredAction;
import com.ntb.controllers.forms.LandForm;
import com.ntb.entities.Lands;
import com.ntb.entities.PermitDetails;
import com.ntb.models.LandPlansLaidDAO;
import com.ntb.models.LandStatusDAO;
import com.ntb.models.LandsDAO;
import com.ntb.models.LocationsDAO;
import com.ntb.models.PermitDetailDAO;
import com.ntb.models.impl.LandPlansLaidDAOImpl;
import com.ntb.models.impl.LandStatusDAOImpl;
import com.ntb.models.impl.LandsDAOImpl;
import com.ntb.models.impl.LocationsDAOImpl;
import com.ntb.models.impl.PermitDetailDAOImpl;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author Thinh Hung
 */
public class LandAction extends SecuredAction {

    private List<String> errorMessages = new ArrayList();
    private List<String> successMessages = new ArrayList();

    @Override
    public ActionForward ntbExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {

        ActionForward forward = mapping.getInputForward();
        LandForm landForm = (LandForm) form;
        LandsDAO landDao = new LandsDAOImpl();
        String action = landForm.getAction();

        errorMessages = new ArrayList();
        successMessages = new ArrayList();


        if ("savePermit".equalsIgnoreCase(action)) {
            // Save Permit Details
            Lands land = landDao.getRow(landForm.getLandID());
            PermitDetailDAO permitDao = new PermitDetailDAOImpl();
            boolean isSuccess = true;

            PermitDetails permit = new PermitDetails();
            permit.setIssuerName(landForm.getIssuerName());
            permit.setIssuedDate(landForm.getIssuedDate());
            permit.setSignerName(landForm.getSignerName());
            permit.setDescription(landForm.getDescription());
            if ("building".equalsIgnoreCase(landForm.getPermitType())) {
                permit.setPermitID(land.getBuildingPermitID());
                if (land.getBuildingPermitID() > 0) {
                    int id = permitDao.update(permit);
                    if (id <= 0) {
                        isSuccess = false;
                    }
                } else {
                    int id = permitDao.add(permit);
                    if (id > 0) {
                        landDao.updateBuildingPermitID(land.getLandID(), id);
                        landDao.updateStatus(land.getLandID(), "RB");
                    } else {
                        isSuccess = false;
                    }
                }
            } else if ("occupancy".equalsIgnoreCase(landForm.getPermitType())) {
                permit.setPermitID(land.getOccupancyPermitID());
                if (land.getOccupancyPermitID() > 0) {
                    int id = permitDao.update(permit);
                    if (id <= 0) {
                        isSuccess = false;
                    }
                } else {
                    int id = permitDao.add(permit);
                    if (id > 0) {
                        landDao.updateOccupancyPermitID(land.getLandID(), id);
                        landDao.updateStatus(land.getLandID(), "RO");
                    } else {
                        isSuccess = false;
                    }
                }
            } else {
                isSuccess = false;
            }
            if (isSuccess) {
                if (landForm.getPermitID() > 0) {
                    successMessages.add("The permit has been saved.");
                } else {
                    successMessages.add("The permit has been added. The status of the land successfully updated.");
                }
            } else {
                errorMessages.add("An error occured, please try again later.");
            }
            forward = viewLand(landDao, landForm, request, mapping);
        } else if ("editBP".equalsIgnoreCase(action)) {
            // Show Edit Building Permit Page

            Lands land = landDao.getRow(landForm.getLandID());
            PermitDetailDAO permitDao = new PermitDetailDAOImpl();
            PermitDetails permit = permitDao.getRow(land.getBuildingPermitID());
            String permitType = "building";
            forward = editPermit(landForm, permitType, permit, mapping);
        } else if ("editOP".equalsIgnoreCase(action)) {
            // Show Edit Occupancy Permit Page

            Lands land = landDao.getRow(landForm.getLandID());
            PermitDetailDAO permitDao = new PermitDetailDAOImpl();
            PermitDetails permit = permitDao.getRow(land.getOccupancyPermitID());
            String permitType = "occupancy";
            forward = editPermit(landForm, permitType, permit, mapping);
        } else if ("save".equalsIgnoreCase(action)) {
            // Save

            forward = updateLand(landForm, landDao, mapping);
            if (forward == null) {
                forward = viewLand(landDao, landForm, request, mapping);
            }
        } else if ("save & exit".equalsIgnoreCase(action)) {
            // Save & Back to list

            forward = updateLand(landForm, landDao, mapping);
            forward = forward == null ? mapping.findForward("landListing") : forward;
        } else if ("edit".equalsIgnoreCase(action)) {
            // Show Edit Page

            Lands land = landDao.getRow(landForm.getLandID());

            landForm.setLandID(land.getLandID());
            landForm.setAddress(land.getAddress());
            landForm.setLocationID(land.getLocationID());
            landForm.setPlanID(land.getPlanID());
            landForm.setLandArea(land.getLandArea() + "");
            landForm.setNearByLandMarks(land.getNearByLandMarks());
            landForm.setPurchasedCost(land.getPurchasedCost() + "");
            landForm.setPurchasedDate(land.getPurchasedDate());

            LocationsDAO locationsDao = new LocationsDAOImpl();

            request.setAttribute("locationList", locationsDao.getList());

            LandPlansLaidDAO planDao = new LandPlansLaidDAOImpl();
            request.setAttribute("planList", planDao.getList());

            LandStatusDAO statusDao = new LandStatusDAOImpl();
            request.setAttribute("statusList", statusDao.getStatusTable());

            forward = mapping.findForward("landEdit");
        } else if ("UpdateStatus".equalsIgnoreCase(action)) {
            // Update Status

            if ("RB".equalsIgnoreCase(landForm.getStatusCode())) {
                landForm.setPermitType("building");
                forward = mapping.findForward("landPermitCreate");
            } else if ("RO".equalsIgnoreCase(landForm.getStatusCode())) {
                landForm.setPermitType("occupancy");
                forward = mapping.findForward("landPermitCreate");
            } else {
                if (landDao.updateStatus(landForm.getLandID(), landForm.getStatusCode()) > 0) {
                    successMessages.add("The status of the land successfully updated.");
                } else {
                    errorMessages.add("There was an error updating the status of this land. Can't re-update the status.");
                }
                forward = viewLand(landDao, landForm, request, mapping);
            }
        } else if (landForm.getLandID() > 0) {
            // Show Detail Page

            forward = viewLand(landDao, landForm, request, mapping);
        } else {
            // Show Add Page

            LocationsDAO locationsDao = new LocationsDAOImpl();
            request.setAttribute("locationList", locationsDao.getList());

            LandPlansLaidDAO planDao = new LandPlansLaidDAOImpl();
            request.setAttribute("planList", planDao.getList());

            LandStatusDAO statusDao = new LandStatusDAOImpl();
            request.setAttribute("statusList", statusDao.getStatusTable());

            landForm.setLandID(0);
        }

        request.setAttribute("errorMessages", errorMessages);
        request.setAttribute("successMessages", successMessages);

        return forward;
    }

    /**
     * Load Edit Permit Page
     * 
     * @param landForm
     * @param permitType
     * @param permit
     * @param mapping
     * @return
     */
    private ActionForward editPermit(LandForm landForm, String permitType, PermitDetails permit, ActionMapping mapping) {
        ActionForward forward;

        landForm.setPermitType(permitType);
        landForm.setPermitID(permit.getPermitID());
        landForm.setIssuerName(permit.getIssuerName());
        landForm.setIssuedDate(permit.getIssuedDate());
        landForm.setSignerName(permit.getSignerName());
        landForm.setDescription(permit.getDescription());
        forward = mapping.findForward("landPermitEdit");
        return forward;
    }

    /**
     * Update Land
     * 
     * @param landForm
     * @param landDao
     * @param mapping
     * @return
     */
    private ActionForward updateLand(LandForm landForm, LandsDAO landDao, ActionMapping mapping) {
        ActionForward forward;
        Lands land = new Lands();

        land.setLandID(landForm.getLandID());
        land.setAddress(landForm.getAddress());
        land.setLocationID(landForm.getLocationID());
        land.setPlanID(landForm.getPlanID());

        int area = 0;
        try {
            area = Integer.parseInt(landForm.getLandArea());
        } catch (Exception ex) {
        }
        land.setLandArea(area);

        land.setNearByLandMarks(landForm.getNearByLandMarks());

        int purchasedCost = 0;
        try {
            purchasedCost = Integer.parseInt(landForm.getPurchasedCost());
        } catch (Exception ex) {
        }
        land.setPurchasedCost(purchasedCost);

        land.setPurchasedDate(landForm.getPurchasedDate());

        if (land.getLandID() > 0) {
            Lands temp = landDao.getRow(land.getLandID());
            if (temp == null) {
                errorMessages.add("Land not found!");
                forward = mapping.findForward("landListing");
            } else {

                landDao.update(land);
                successMessages.add("The land \"" + land.getLandID() + "\" has been saved.");
                return null;
            }
        } else {
            landDao.add(land);
            successMessages.add("The new land has been added.");
            forward = mapping.findForward("landListing");
        }
        return forward;
    }

    /**
     * Load Detail Page
     * 
     * @param landDao
     * @param landForm
     * @param request
     * @param mapping
     * @return
     */
    private ActionForward viewLand(LandsDAO landDao, LandForm landForm, HttpServletRequest request, ActionMapping mapping) {
        ActionForward forward;
        Lands land = landDao.getRow(landForm.getLandID());
        request.setAttribute("land", land);

        LandStatusDAO landStatusDao = new LandStatusDAOImpl();
        request.setAttribute("statusHistory", landStatusDao.getList(land.getLandID()));

        LocationsDAO locationDao = new LocationsDAOImpl();

        List yearList = locationDao.getCostHistoryYear(land.getLocationID());

        request.setAttribute("yearList", yearList);

        String year = "";
        try {
            if (landForm.getYear() != null && !"".equals(landForm.getYear())) {
                year = landForm.getYear();
            } else {
                year = yearList.get(0).toString();
            }
        } catch (Exception ex) {
        }
        landForm.setYear(year);

        request.setAttribute("selectYear", year);

        request.setAttribute("locationName", land.getLocationName());

        List costHistory = locationDao.getCostHistory(land.getLocationID(), year);
        request.setAttribute("costHistory", costHistory);

        PermitDetailDAO permitDao = new PermitDetailDAOImpl();
        boolean havePermit = false;
        if (land.getBuildingPermitID() > 0) {
            havePermit = true;
            request.setAttribute("buildingPermit", permitDao.getRow(land.getBuildingPermitID()));
        }
        if (land.getOccupancyPermitID() > 0) {
            havePermit = true;
            request.setAttribute("occupancyPermit", permitDao.getRow(land.getOccupancyPermitID()));
        }
        if (havePermit) {
            request.setAttribute("havePermit", true);
        }

        forward = mapping.findForward("landDetail");
        return forward;
    }
}
